# == Schema Information
#
# Table name: addresses
#
#  id           :integer          not null, primary key
#  user_id      :integer
#  address_type :string
#  contact_name :string
#  cellphone    :string
#  address      :string
#  zipcode      :string
#  region       :string
#  created_at   :datetime         not null
#  updated_at   :datetime         not null
#  street_id    :string
#  deleted_at   :datetime
#

class Address < ApplicationRecord
  acts_as_paranoid without_default_scope: true

  validates :user_id, presence: true
  validates :address_type, presence: true
  validates :contact_name, presence: { message: "收货人不能为空" }
  validates :cellphone, presence: { message: "手机号不能为空" }
  validates :address, presence: { message: "地址不能为空" }
  validates :street_id, presence: { message: "街道不能为空" }

  belongs_to :user

  attr_accessor :set_as_default

  after_save :set_as_default_address
  before_destroy :remove_self_as_default_address

  module AddressType
    User = 'user'
    Order = 'order'
    NONE = "不要求填写详细地址"
  end

  def province
    ChinaCity.get(ChinaCity.province(self.street_id.to_s))
  end

  def city
    ChinaCity.get(ChinaCity.city(self.street_id.to_s))
  end

  def district
    ChinaCity.get(ChinaCity.district(self.street_id.to_s))
  end

  def street
    ChinaCity.get(self.street_id.to_s) + self.address
  end

  def as_json(options={})
    super({methods: [:province, :city, :district, :street]}.merge(options))
  end

  def get_full
    (ChinaCity.get(self.street_id.to_s, prepend_parent: true) + self.address).gsub(/(#{(Address::AddressType::NONE)}|市辖区|县)/, '')
  end

  private

  def set_as_default_address
    # if self.set_as_default.to_i == 1 && self.user && self.user.default_address.nil?

    return unless self.user
    if self.set_as_default.to_i == 1 && self.user || self.user.default_address.nil?
      self.user.default_address = self
      self.user.save!
    else
      remove_self_as_default_address
    end
  end

  def remove_self_as_default_address
    if self.user && self.user.default_address == self
      self.user.default_address = nil
      self.user.save!
    end
  end
end
